/*
 * @Author: taiyunhang
 * @Date: 2018-04-10 20:13:55
 * */

// import BMap from 'BMap';
import { Toast } from 'mint-ui';

const BMap = window.BMap;

const map = new BMap.Map();
const myGeo = new BMap.Geocoder();
const localSearch = new BMap.LocalSearch(map);

class BmapApi {
  constructor() {
    // console.log(BMap)
  }

  /**
   * @func
   * @desc 实例化一个地图对象
   * @param {string} id
   */
  map(id) {
    let bMap = new BMap.Map(id);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个标注
   * @param {Object} pt
   * @param {Object} opts
   */
  marker(pt, opts) {
    let bMap = new BMap.Marker(pt, opts);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个图标
   * @param {string} img
   * @param {Object} size
   * @param {Object} opts
   */
  icon(img, size, opts) {
    let bMap = new BMap.Icon(img, size, opts);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个百度label组件
   * @param {string} content
   * @param {Object} opts
   */
  label(content, opts) {
    let bMap = new BMap.Label(content, opts);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个设置大小对象
   * @param {number} w
   * @param {number} h
   */
  size(w, h) {
    let bMap = new BMap.Size(w, h);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个坐标点
   * @param {number} lng
   * @param {number} lat
   */
  point(lng, lat) {
    let bMap = new BMap.Point(lng, lat);
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个Geolocation对象
   */
  geolocation() {
    let bMap = new BMap.Geolocation();
    return bMap;
  }

  /**
   * @func
   * @desc 实例化一个Geocoder对象
   */
  geocoder() {
    let bMap = new BMap.Geocoder();
    return bMap;
  }

  /**
   * @func
   * @desc 地图输入提示
   * @param {string} inputId 需绑定的输入框id
   */
  bmapAutocomplete(inputId, callback) {
    let ac = new BMap.Autocomplete({
      // 建立一个自动完成的对象
      input: inputId
    });
    ac.addEventListener('onhighlight', function(e) {
      console.log(e);
      // 鼠标放在下拉列表上的事件
    });
    ac.addEventListener('onconfirm', function(e) {
      // 鼠标点击下拉列表后的事件
      let _value = e.item.value;
      let myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
      callback(myValue);
    });
    return ac;
  }

  /**
   * @desc 地址转经纬度
   * @param {string} Baddress 需解析的地址
   */
  addressToPoint(Baddress) {
    const p1 = new Promise((resolve, reject) => {
      if (Baddress) {
        myGeo.getPoint(
          Baddress,
          function(point) {
            if (point) {
              let pt = new BMap.Point(point.lng, point.lat);
              resolve(pt);
            } else {
              localSearch.setSearchCompleteCallback(function(searchResult) {
                let poi = searchResult.getPoi(0);
                if (poi) {
                  let point = poi.point;
                  let pt = new BMap.Point(point.lng, point.lat);
                  resolve(pt);
                } else {
                  reject('未解析到结果！');
                }
              });
              localSearch.search(Baddress);
            }
          },
          '中国'
        );
      } else {
        reject('未解析到结果！');
      }
    });
    return p1;
  }

  /**
   * @desc 经纬度转地址
   * @param {Object} pt 需逆地址解析的经纬度
   */
  pointToAddress(pt) {
    const p2 = new Promise((resolve, reject) => {
      myGeo.getLocation(pt, function(rs) {
        if (rs) {
          console.log(rs);
          // let addComp = rs.addressComponents;
          resolve(rs);
        } else {
          reject('未解析到结果！');
        }
      });
    });
    return p2;
  }

  /**
   * @desc 根据起始地计算距离
   * @param {Object} startPoint 出发地经纬度
   * @param {Object} endPoint 目的地经纬度
   */
  getDistance(startPoint, endPoint) {
    const p3 = new Promise((resolve, reject) => {
      let searchComplete = function(results) {
        console.log(results);
        /* eslint-disable */
        if (transit.getStatus() !== BMAP_STATUS_SUCCESS) {
          reject('未获取距离结果！');
          return;
        }
        /* eslint-disable */
        let plan = results.getPlan(0);
        // let time = plan.getDuration(true); //获取时间
        let distance = plan.getDistance(false); // 获取距离 true返回距离字符串（包含单位）false仅返回数值（单位米）
        distance = (distance / 1000).toFixed(0);
        resolve(distance);
      };
      let transit = new BMap.DrivingRoute(map, {
        onSearchComplete: searchComplete
      });
      transit.search(startPoint, endPoint);
    });
    return p3;
  }

  /**
   * @func
   * @desc 定位
   */
  getCurrentPosition() {
    return new Promise((resolve, reject) => {
      if (navigator.geolocation) {
        var geolocation = this.geolocation();
        var geoc = this.geocoder();
        geolocation.getCurrentPosition(
          r => {
            if (geolocation.getStatus() === 0) {
              geoc.getLocation(r.point, rs => {
                var addComp = rs.addressComponents;
                sessionStorage.longitude = rs.point.lng;
                sessionStorage.latitude = rs.point.lat;
                sessionStorage.gps = addComp.city;
                sessionStorage.addComp = JSON.stringify(addComp);
                // sessionStorage.myAddress = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                resolve('');
              });
            } else {
              Toast({
                message: 'failed' + geolocation.getStatus(),
                position: 'middle'
              });
            }
          },
          { enableHighAccuracy: true }
        );
      } else {
        Toast({
          message: '浏览器不支持地理定位。',
          position: 'middle'
        });
      }
    });
  }
}

export default new BmapApi();
